// pages/personal/personal.js
const util = require('../../utils/util.js')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    /*  */
    userInfo_chezhu: {},
    /*  */
    avatarUrl: '',
    nickName: '',
    mobile: '',
    showOpenSetting: false,  //openSetting-button
    /*  */
    adviceBtnData: [
      {}
    ],
    /*  */
    bindPhone: [
      {}
    ],
    /*  */
    toggleModal: true,
    getVcode: {
      initText: '获取验证码',
      time: 61,
      djsing: false,
      mobile: '', //手机号码
      code: ''  //验证码
    },
    /*  */
    djs: null
  },
  /*  */
  showAdvicePage: function (e) {
    let { index } = e.currentTarget.dataset
    app.globalData.setNeedAnimation.call(this, 'adviceBtnData', this.data.adviceBtnData, index).then(() => {
      wx.navigateTo({
        url: '/pages/advice/advice'
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    /*  */
    this.getDataByUserLocation()
  },
  /* 授权订阅消息 */
  SubscribeMessage: function () {
    return new Promise((resolve,reject)=>{
      wx.requestSubscribeMessage({
        tmplIds: [this.data.userInfo_chezhu.subScribeMessageCode], // 此处可填写多个模板 ID，但低版本微信不兼容只能授权一个
        success: res => {
        console.log(res)
        if (res[this.data.userInfo_chezhu.subScribeMessageCode] == 'accept') {
          resolve()
        } else {
          resolve()
        }
        },
        fail: err => {
          resolve()
        }
      })
    })
  },
  /* 获取登录用户的后台信息 */
  user_loginWx: function () {
    return new Promise((resolve, reject) => {
      wx.request({
        url: app.globalData.Url + '/loginWxCar',
        method: 'POST',
        header: {
          'content-type': app.globalData.contentType
        },
        data: util.json2Form({
          avatar: this.data.userInfo_chezhu.userInfo.avatar,  //头像
          nickName: this.data.userInfo_chezhu.userInfo.nickName,  //昵称
          openid: this.data.userInfo_chezhu.openid,    //openid
        }),
        success: res => {
          console.log(res)
          this.setData({
            'userInfo_chezhu.token': res.data.body.token,
            'userInfo_chezhu.header.cartoken': res.data.body.token,
            'userInfo_chezhu.userid': res.data.body.userid,
            'userInfo_chezhu.mobile': res.data.body.mobile||'',
          })
          //信息存缓存
          wx.setStorageSync('userInfo_chezhu', this.data.userInfo_chezhu)
          //
          if(this.data.userInfo_chezhu.mobile){
            //
            wx.switchTab({
              url: '/pages/index/index'
            })
          }else{
            //
            wx.navigateTo({
              url: '/pages/login2/login2'
            })
          }
          resolve()
        },
        fail: err => {
          reject('获取与登录用户对应的后台信息失败')
        }
      })
    })
  },
  /* 获取用户信息 */
  getUserInfoFn: function (e) {
    console.log(e)
    // wx.navigateTo({
    //   url: '/pages/login2/login2',
    // })
    if (e.detail.errMsg == 'getUserInfo:ok') {
      this.setData({
        'userInfo_chezhu.userInfo': e.detail.userInfo
      })
      //信息存缓存
      wx.setStorageSync('userInfo_chezhu', this.data.userInfo_chezhu)
      //
      wx.showLoading({
        title: '',
        mask:true
      })
      //
      this.user_loginWx().then(() => {
        
      }).catch(errMsg => {
        wx.showModal({
          title: '提示',
          content: errMsg + '',
          showCancel: false,
          confirmColor: app.globalData.modalConfirmColor
        })
      }).finally(() => {
        wx.hideLoading()
      })
    } else {
      
    }
  },
  /* 去登录 */
  goToLogin: function(){
    wx.navigateTo({
      url: '/pages/login2/login2',
    })
  },
  /* 退出登录 */
  exitLogin: function(){
    wx.showModal({
      title:'提示',
      content:'确定退出登录吗？',
      success: res=>{
        if(res.confirm){
          wx.showLoading({
            title: '退出中...',
            mask:true
          })
          // 清空手机号码
          wx.request({
            url: app.globalData.Url + '/wx/clearUserMobile',
            method: 'POST',
            header: this.data.userInfo_chezhu.header,
            data: util.json2Form({
              type: this.data.userInfo_chezhu.miniProType
            }),
            success: res => {
              console.log(res)
              //判断token是否过期
              if(app.globalData.check_token(res.data.code))return new Promise((resolve,reject)=>{})
              if (res.data.code == '1') {
                wx.clearStorageSync('userInfo_chezhu')
                //
                wx.navigateTo({
                  url:'/pages/guide/guide'
                })
              } else {
                wx.showToast({
                  icon: 'none',
                  title: res.data.msg + ''
                })
              }
            },
            fail: err => {
              console.log(err)
              wx.showToast({
                icon: 'none',
                title: '清空手机号码失败'
              })
              reject()
            },
            complete: () => {
              wx.hideLoading()
            }
          })
        }
      }
    })
  },
  /* 显示个人位置信息 */
  showPersonalPos: function(){
    wx.getSetting({
      success: res=>{
        console.log(res)
        if(res.authSetting['scope.userLocation']){
          app.globalData.getLocation().then(res=>{
            //console.log(res)
            wx.openLocation({
              latitude: res.latitude,
              longitude: res.longitude,
              scale: 18
            })
          })
        }else{
          wx.showModal({
            title:'提示',
            content:'暂未打开位置授权，请在个人设置中开启！',
            showCancel:false
          })
        }
      },
      fail: err=>{
        wx.showModal({
          title:'提示',
          content:'暂未打开位置授权，请在个人设置中开启！',
          showCancel:false
        })
      }
    })
  },
  /* 解析经纬度 */
  latLng2Address: function(res){
    wx.request({
      url: app.globalData.Url + '/latLng2Address',
      method: 'POST',
      header: this.data.userInfo_chezhu.header,
      data: util.json2Form({
        latLng: res.latitude + ',' + res.longitude
      }),
      success: res => {
        console.log(res)
        //判断token是否过期
        if(app.globalData.check_token(res.data.code))return new Promise((resolve,reject)=>{})
        this.setData({
          'userInfo_chezhu.address': res.data.formatted_address
        })
      },
      fail: err => {
        wx.showToast({
          icon:'none',
          content:'解析经纬度地址失败'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },
  /*  */
  getDataByUserLocation: function(){
    //获取用户信息
    this.setData({
      userInfo_chezhu: app.globalData.get_userInfo()
    })
    if(this.data.userInfo_chezhu.mobile){
      if (this.data.userInfo_chezhu.isOpenScopePos) {
        app.globalData.getLocation().then(res => {
          //console.log(res)
          this.latLng2Address(res)
        }).catch(err => {

        })
      } else {
        this.setData({
          'userInfo_chezhu.address': '未授权获取位置信息'
        })
        //
        wx.authorize({
          scope: 'scope.userLocation',
          success: res => {
            console.log(res)
            if (res.errMsg === 'authorize:ok') {
              //
              this.setData({
                'userInfo_chezhu.isOpenScopePos':true
              })
              //信息存缓存
              wx.setStorageSync('userInfo_chezhu', this.data.userInfo_chezhu)
              //
              app.globalData.getLocation().then(res => {
                console.log(res)
                this.latLng2Address(res)
              }).catch(err => {

              })
            } else {
              this.setData({
                'userInfo_chezhu.address': '未授权获取位置信息，点击设置'
              })
              wx.hideLoading()
            }
          },
          fail: err => {
            this.setData({
              'userInfo_chezhu.address': '未授权获取位置信息，点击设置'
            })
            wx.hideLoading()
          }
        })
      }
    }
  },
  /* 获取openSetting结果 */
  getOpenSettingData: function (e) {
    console.log(e)
    let { authSetting } = e.detail
    if (authSetting['scope.userLocation']) {
      this.setData({
        'userInfo_chezhu.isOpenScopePos': true
      })
      //信息存缓存
      wx.setStorageSync('userInfo_chezhu', this.data.userInfo_chezhu)
      //
      this.getDataByUserLocation()
    } else {
      this.setData({
        'userInfo_chezhu.address': '未授权获取位置信息，点击设置'
      })
      wx.showToast({
        icon: 'none',
        title: '请开启位置授权'
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})